<?php

namespace core\utils;
use core\library\Input;

class RouterRule {
    private $url;
    // 允许的方法
    // 可选的值为 GET POST ALL
    private $method;
    private $trueUrl;

    const ALL_ALLOW_METHOD = [
        'GET', 'POST', 'ALL'
    ];

    /**
     * Rules constructor.
     * @param $url
     * @param $method
     * @param $trueUrl
     */
    public function __construct(string $url, string $method, $trueUrl = null)
    {
        $this->url = $url;
        $method = strtoupper($method);
        if (in_array($method, self::ALL_ALLOW_METHOD))
            $this->method = $method;
        $this->trueUrl = $trueUrl ?? $url;
    }

    /**
     * 返回映射之前的url
     * @return string
     */
    public function getUrl(): string {
        return $this->url;
    }


    /**
     * @return string
     */
    public function getMethod(): string {
        return $this->method;
    }

    /**
     * 获取映射之后的url
     * @return string
     */
    public function getTrueUrl(): string {
        return $this->trueUrl;
    }

    /**
     * 检查url是否击中该规则
     * @param $url
     * @return bool
     */
    public function match($url) : bool
    {
        $pathVariables = [];
        // 解析设置的url
        $settingUrl = explode('/', ltrim($this->url, '/'));
        $inputUrl = explode('/', ltrim($url, '/'));

        foreach ($settingUrl as $key=>$value) {
            if (@$value[0] == '<' && $value[strlen($value) - 1] == '>') {
                $str = rtrim(ltrim($value, '<'), '>');
                $divPos = strpos($str, ':');
                if (false === $divPos) {
                    // 单纯的正则匹配
                    $pattern = '/^' . substr($str, 0) . '$/';
                    if (!preg_match($pattern, $inputUrl[$key])) {
                        return false;
                    }
                } else {
                    // 不但要正则匹配，还要搞个pathVariables
                    $name = substr($str, 0, $divPos);
                    $pattern = '/^' . substr($str, $divPos + 1) . '$/';
                    if (preg_match($pattern, $inputUrl[$key])) {
                        $pathVariables[$name] = $inputUrl[$key];
                    } else {
                        return false;
                    }
                }
            } else if (!isset($inputUrl[$key]) || $value != $inputUrl[$key]) {
                // 传入的参数不存在或者和配置的不一致
                return false;
            }
        }
        // 设置pathVariable
        $input = Input::getInstance();
        $input->setPathVariable($pathVariables);
        return true;
    }
}